var uid = -1;
//获取点击的链接url
var arrIdx = [];
var tabElement;
$(function() {

	layui.use(['element', "layer", "tree", 'form'], function() {
		tabElement = layui.element;
			var layer = layui.layer,
			tree = layui.tree,
			form = layui.form;
		var orgName = $('#orgName').val();
		if (orgName != null && orgName != '') {
			$('.home-title').html('旭云智慧平台(' + orgName + 'ERP)');
			$('title').html('旭云智慧平台(' + orgName + 'ERP)');
		}
		/**初始化站点**/
		initOrigin();
		/**检测是否选择站点**/
		checkStation();

		tabElement.tabAdd('indexTab', {
			title: '首页面板',
			id: '223',
			content: '<iframe frameborder="0" name="content" scrolling="yes" width="100%" height="100%"  src="/console/panel"></iframe>',
		});
		arrIdx.push('223');
		tabElement.tabChange('indexTab', '223'); //切换到：用户管理

		$(".left-menu").on("click","ul li",function(){
			$(this).siblings().removeClass("layui-nav-itemed");
		});
		tabElement.on('nav(leftNav)', function(ele) {
			// var orgId = $('.station-btn').attr('data-id');
			// if (isNull(orgId) || orgId == -1) {
			// 	layer.msg("请输选择站点！");
			// 	return;
			// }
			//			console.log($(this).children().attr("data-url")); //得到当前点击的DOM对象
			var url = ele.children().attr("data-url");
			var id = ele.children().attr("data-id");
			var type = ele.children().attr('data-type');
			// var url = "pages/message/information/information.html";
			//判断是否已经存在改页面
			if(arrIdx.indexOf(id) == "-1") {
				if (!isNull(type) && (type == 1 || type == 3)) {//旭科云
					// var result = oauthToken();
					var username = $('.username').val();
					var oauthType = $('.oauthType').val();
					var timestamp = $('.timestamp').val();
					var echostr = $('.echostr').val();
					var token = $('.authToken').val();
					if (!isNull(username) && !isNull(oauthType) && !isNull(echostr) && !isNull(token)) {
						console.log('cacheUser')
						if (type == 1)
							url = "https://surker.chixugroup.com" + url;
						else
							url = "https://cloud.chixugroup.com" + url;

						// url = "http://localhost:8094" + url;
						url += '?username=' + username + '&oauthType=' + oauthType + '&timestamp='
							+ timestamp + '&echostr=' + echostr + '&oauthToken=' + token;
						tabElement.tabAdd('indexTab', {
							title: ele.text(),
							id: id,
							content: '<iframe frameborder="0" name="content" scrolling="yes" width="100%" height="100%"  src="' + url + '"></iframe>',
						});
						arrIdx.push(id);
						tabElement.tabChange('indexTab', id); //切换到：用户管理
					} else {
						console.log('loadUser')
						$.ajax({
							type: "POST",
							url: "/sys_user/oauth/token",
							async: true,
							dataType: 'json',
							timeout: 5000,
							success: function(res) {
								if(res.code == 0) {
									var data = res.data;
									$('.username').val(data.username);
									$('.oauthType').val(data.oauthType);
									$('.timestamp').val(data.timestamp);
									$('.echostr').val(data.echostr);
									$('.authToken').val(data.token);
									console.log(data)
									if (type == 1)
										url = "https://surker.chixugroup.com" + url;
									else
										url = "https://cloud.chixugroup.com" + url;
									// url = "http://localhost:8094" + url;
									url += '?username=' + data.username + '&oauthType=' + data.oauthType + '&timestamp='
										+ data.timestamp + '&echostr=' + data.echostr + '&oauthToken=' + data.token;
									tabElement.tabAdd('indexTab', {
										title: ele.text(),
										id: id,
										content: '<iframe frameborder="0" name="content" scrolling="yes" width="100%" height="100%"  src="' + url + '"></iframe>',
									});
									arrIdx.push(id);
									tabElement.tabChange('indexTab', id); //切换到：用户管理
								} else {
									layer.msg(res.msg);
								}

							},
							error: function(res) {
								layer.msg(res.msg);
							},
							complete: function(XMLHttpRequest, status) {
								if(status == 'timeout') {
									layer.msg("请求超时");
								}
							}
						});
					}

				} else {
					tabElement.tabAdd('indexTab', {
						title: ele.text(),
						id: id,
						content: '<iframe frameborder="0" name="content" scrolling="yes" width="100%" height="100%"  src="' + url + '"></iframe>',
					});
					arrIdx.push(id);
					tabElement.tabChange('indexTab', id); //切换到：用户管理
				}
			} else {
				tabElement.tabChange('indexTab', id); //切换到：用户管理
				return;
			}
		});
		tabElement.on('tab(indexTab)', function(data) {
			var index = $(".indexTabs .layui-this").attr("lay-id");
			leftMenuChange(index);
		});
		//点击删除时
		tabElement.on('tabDelete(indexTab)', function(data) {
			var id = $(this).parent().attr("lay-id");
			//删除重复的id
			arrIdx.splice($.inArray(id, arrIdx), 1);
			var index = $(".indexTabs .layui-this").attr("lay-id");
			//			console.log(index);
			//			var a = $(".left-menu ul dl a");
			//			$.each(a, function(i,v) {
			//				if($(this).attr("data-id"))
			//			});
			leftMenuChange(index);
		});

		$(".stationModal .close").on("click", function() {
			$(".stationModal").hide();
			$(".stationModal input").val("");
			$(".stationModal select").val("");
			$(".stationModal textarea").val("");
			form.render();
		});

		/**选择站点**/
		$('.stationModal .btn-submit').on('click', function () {
			var orgId = $('.stationModal .station').val();
			if (isNull(orgId) || orgId == -1) {
				layer.msg("请选择站点！");
				return;
			}
			var loading = layer.load();
			$.ajax({
				type: "POST",
				url: "/console/chose/station",
				async: true,
				dataType: 'json',
				timeout: 5000,
				data:{ originId : orgId},
				success: function(res) {
					layer.close(layer.load());
					if(res.code == 0) {
						$('.station-btn').attr('data-id', res.data.originId);
						$('.station-btn').html('站点(' + res.data.originName + ')');
						$('.user-logo-btn').html(res.data.name);
						$('.stationModal').hide();
						initLeftMenu(tabElement);
					} else {
						layer.msg(res.msg);
						layer.close(loading);
						return;
					}

				},
				error: function(res) {
					layer.msg("系统异常,请稍后再试");
					layer.close(loading);
					return;
				},
				complete: function(XMLHttpRequest, status) {
					if(status == 'timeout') {
						layer.msg("请求超时");
						layer.close(loading);
						return;
					}
				}
			});
		});

		//退出
		$(".indexHeader .loginOut-btn").on("click", function() {
			var loading = layer.load();
			$.ajax({
				type: "POST",
				url: "/console/logout",
				async: true,
				dataType: 'json',
				data: {
					uid: uid
				},
				timeout: 5000,
				success: function(res) {
					layer.close(layer.load());
					console.log(res);
					if(res.code == 0) {
						//具体数据列表
						window.location.href = '/console/login';
					} else {
						layer.msg(res.msg);
						layer.close(loading);
						return;
					}

				},
				error: function(res) {
					layer.msg(res.msg);
					layer.close(loading);
					return;
				},
				complete: function(XMLHttpRequest, status) {
					if(status == 'timeout') {
						layer.msg("请求超时");
						layer.close(loading);
						return;
					}
				}
			});
		})

		$(".indexHeader .updatePwd-btn").on("click", function() {
			$(".updatePwdModal").show();
		})
		$(".updatePwdModal .close").on("click", function() {
			$(".updatePwdModal").hide();
		})
		$(".updatePwdModal .btn-submit").on("click", function() {
			var oldPwd = $(".oldPwd").val();
			//未判断旧密码是否正确
			var newPwd1 = $(".newPwd1").val();
			var newPwd2 = $(".newPwd2").val();
			if(oldPwd == null || oldPwd == undefined || oldPwd == '') {
				layer.msg("旧密码密码不能为空");
				return
			}
			if(newPwd1 == null || newPwd1 == undefined || newPwd1 == '') {
				layer.msg("新密码不能为空");
				return;
			}
			if(newPwd2 == null || newPwd2 == undefined || newPwd2 == '') {
				layer.msg("确认密码不能为空");
				return;
			}
			if(newPwd1 != newPwd2) {
				layer.msg("新密码与确认密码不一致，请重新输入！");
				return;
			}

			var loading = layer.load();
			$.ajax({
				type: "put",
				url: "/sys_user/update/password",
				async: true,
				dataType: 'json',
				data: {
					uid: uid,
					oldPassword: oldPwd,
					newPassword: newPwd2
				},
				timeout: 5000,
				success: function(res) {
					layer.close(layer.load());
					console.log(res);
					if(res.code == 0) {
						//具体数据列表
						layer.msg(res.msg);
						$(".updatePwdModal").hide();
						$(".updatePwdModal input").val("");
					} else {
						layer.msg(res.msg);
						layer.close(loading);
						return;
					}

				},
				error: function(res) {
					layer.msg(res.msg);
					layer.close(loading);
					return;
				},
				complete: function(XMLHttpRequest, status) {
					if(status == 'timeout') {
						layer.msg("请求超时");
						layer.close(loading);
						return;
					}
				}
			});
		})

		$(".zdMenu").on("click", function() {
			if($(".left-menu").hasClass("out")) {
				$(this).find("i").html("&#xe65a;");
				$(".left-menu").removeClass("out").stop().animate({
					"left": "0"
				}, 300);
				$(".layui-layout-admin .layui-body").stop().animate({
					"left": "200px"
				}, 300);
			} else {
				$(this).find("i").html("&#xe65b;");
				$(".left-menu").addClass("out").stop().animate({
					"left": "-200px"
				}, 300);
				$(".layui-layout-admin .layui-body").stop().animate({
					"left": "0"
				}, 300);
			}

		})

		$(".lock-btn").on("click",function(){
			window.sessionStorage.setItem("lockcms",true);
			lockPage();
		})
		// 判断是否显示锁屏
		if(window.sessionStorage.getItem("lockcms") == "true"){
			lockPage();
		}

		/**站点**/
		$('.station-btn').on('click', function () {
			$('.stationModal').show();
		});
		$('.reset-pwd-btn').on('click', function () {
			var loading = layer.load();
			$.ajax({
				type: "PUT",
				url: "/sys_user/reset/password",
				async: true,
				dataType: 'json',
				timeout: 5000,
				success: function(res) {
					layer.close(layer.load());
					console.log(res)
					if(res.code == 0) {
						layer.msg('密码已重置为身份证后六位,退出后即生效~！');
					} else {
						layer.msg(res.msg);
						layer.close(loading);
						return;
					}

				},
				error: function(res) {
					layer.msg(res.msg);
					layer.close(loading);
					return;
				},
				complete: function(XMLHttpRequest, status) {
					if(status == 'timeout') {
						layer.msg("请求超时");
						layer.close(loading);
						return;
					}
				}
			});
		});

		// 解锁
		$("#unlock").on("click",function(){
			if($(this).siblings(".admin-header-lock-input").val() == ''){
				layer.msg("请输入解锁密码！");
			}else{
				if($(this).siblings(".admin-header-lock-input").val() == "123456"){
					window.sessionStorage.setItem("lockcms",false);
					$(this).siblings(".admin-header-lock-input").val('');
					layer.closeAll("page");
					$('#lock-box').hide();
				}else{
					layer.msg("密码错误，请重新输入！");
				}
			}
		});
		$(document).on('keydown', function() {
			if(event.keyCode == 13) {
				$("#unlock").click();
			}
		});

		/**初始化站点**/
		function initOrigin() {
			$.ajax({
				type: "post",
				url: '/sys_origin/query/user/origin',
				async: true,
				dataType: 'json',
				timeout: 30000,
				data: {type:2,status:0},
				success: function(res) {
					// console.log(res)
					if(res.code == 0) {
						if (res.data != null && res.data.length > 0) {
							var html ='请选择';
							$.each(res.data, function(index, val) {
								html += '<option value="' + val.id + '">' + val.originName + '</option>';
							});
						} else {
							$('.stationModal .station').empty().append("<option>您未关联站点,请联系管理人员</option>");
						}
						$('.stationModal .station').empty().append(html);
						form.render();
					} else {
						$('.stationModal .station').empty().append("<option>您未关联站点,请联系管理人员</option>");
						form.render();
					}
				},
				error: function(res) {
					layer.msg("请求失败，请稍后再试！");
					return;
				},
				complete: function(XMLHttpRequest, status) {
					if(status == 'timeout') {
						layer.msg("请求超时，请稍后再试！");
						return;
					}
				}
			});
		}

		/**检查站点**/
		function checkStation() {
			// var originId = $('.station-btn').attr('data-id');
			// if (!isNull(originId))
			// 	return ;
			$('.user-logo-btn').html($('#name').val());
			initLeftMenu(tabElement);
			// var loading = layer.load();
			// $.ajax({
			// 	type: "POST",
			// 	url: "/console/check/station",
			// 	async: true,
			// 	dataType: 'json',
			// 	timeout: 5000,
			// 	success: function(res) {
			// 		layer.close(layer.load());
			// 		if(res.code == 0) {
			// 			$('.station-btn').attr('data-id', res.data.originId);
			// 			$('.station-btn').html('站点(' + res.data.originName + ')');
			// 			$('.user-logo-btn').html(res.data.name);
			// 			initLeftMenu(tabElement);
			// 		} else {
			// 			// layer.msg(res.msg);
			// 			layer.close(loading);
			// 			$('.stationModal').show();
			// 			return;
			// 		}
			//
			// 	},
			// 	error: function(res) {
			// 		layer.msg(res.msg);
			// 		layer.close(loading);
			// 		return;
			// 	},
			// 	complete: function(XMLHttpRequest, status) {
			// 		if(status == 'timeout') {
			// 			layer.msg("请求超时");
			// 			layer.close(loading);
			// 			return;
			// 		}
			// 	}
			// });
		}

		//初始化左侧菜单
		function initLeftMenu(element) {
			var loading = layer.load();
			$.ajax({
				type: "POST",
				url: "/console/load/menu",
				async: true,
				dataType: 'json',
				data:{isDataCheck:$('.isDataCheck').val()},
				timeout: 5000,
				success: function(res) {
					layer.close(layer.load());
					console.log(res)
					if(res.code == 0) {
						//具体数据列表
						var datas = res.data;
						var mList = '';
						// console.log(datas);
						var authToken = $('.authToken').val();
						var isDataCheck = $('.isDataCheck').val();
						var username = $('.username').val();
						var oauthType = $('.oauthType').val();
						var timestamp = $('.timestamp').val();
						var echostr = $('.echostr').val();
						var params = '&username=' + username + '&oauthType=' + oauthType + '&timestamp=' + timestamp + '&echostr=' + echostr;
						$.each(datas, function(index, val) {
							if (val.children != null && val.children.length > 0) {//如果没有子菜单
								var name = val.name;
								var icon = '';
								if (val.icon != null) {
									icon = "<i class='bi " + val.icon + "'>  </i>";
								}
								mList += "<li class='layui-nav-item'>";
								mList += "<a href='javascript:void(0)' data-id ='" + val.id + "'>" + icon
									+ name + convertMenuType(val.type) + "</a>";
								if(val.children != undefined && val.children.length > 0) {
									mList += "<dl class='layui-nav-child'>";
									$.each(val.children, function(i, v) {
										// if (v.type != 5) {
											var icon_ = '';
											if (!isNull(v.icon)) {
												icon_ = "<i class='bi " + v.icon + "'>  </i>";
											}
											if (name == '系统配置') {
												mList += "<dd><a href='javascript:void(0)' data-type='" + v.type + "' data-url='" + v.url + "' data-id ='" + v.id + "'>"
													+ icon_ + v.name + convertMenuType(v.type) + "</a></dd>";
											} else {

												mList += "<dd><a href='javascript:void(0)' data-type='" + v.type + "' data-url='" + v.url + "' data-id ='" + v.id + "'>"
													+ icon_ + v.name + convertMenuType(v.type) + "</a></dd>";
											}
										// }
									});
									mList += "</dl>";
								}
							}
						});
						$(".left-menu .layui-nav").empty().append(mList);
						//渲染导航
						element.render('nav', 'leftNav');

					} else {
						layer.msg(res.msg);
						layer.close(loading);
						return;
					}

				},
				error: function(res) {
					layer.msg(res.msg);
					layer.close(loading);
					return;
				},
				complete: function(XMLHttpRequest, status) {
					if(status == 'timeout') {
						layer.msg("请求超时");
						layer.close(loading);
						return;
					}
				}
			});
		}

		$('.clear-btn').on('click', function () {
			var loading = layer.load();
			$.ajax({
				type: "POST",
				url: "/sys_user/clear/cache",
				async: true,
				dataType: 'json',
				timeout: 5000,
				success: function(res) {
					layer.close(layer.load());
					console.log(res)
					if(res.code == 0) {
						layer.msg('缓存已更新');
					} else {
						layer.msg(res.msg);
						layer.close(loading);
						return;
					}

				},
				error: function(res) {
					layer.msg(res.msg);
					layer.close(loading);
					return;
				},
				complete: function(XMLHttpRequest, status) {
					if(status == 'timeout') {
						layer.msg("请求超时");
						layer.close(loading);
						return;
					}
				}
			});
		});

	});

})

function oauthToken() {
	$.ajax({
		type: "POST",
		url: "/sys_user/oauth/token",
		async: true,
		dataType: 'json',
		timeout: 5000,
		success: function(res) {
			if(res.code == 0) {
				var option = {
					username:res.data.username,
					oauthType: res.data.oauthType,
					timestamp: res.data.timestamp,
					echostr: res.data.echostr
				};
				console.log(option)
				return option;
			} else {
				layer.msg(res.msg);
				return null;
			}

		},
		error: function(res) {
			layer.msg(res.msg);
			return null;
		},
		complete: function(XMLHttpRequest, status) {
			if(status == 'timeout') {
				layer.msg("请求超时");
				return null;
			}
		}
	});
}

function addTabs(id, title, url) {
	if(arrIdx.indexOf(id) == "-1") {
		tabElement.tabAdd('indexTab', {
			title: title,
			id: id,
			content: '<iframe frameborder="0" name="content" scrolling="yes" width="100%" height="100%"  src="' + url + '"></iframe>',
		});
		arrIdx.push(id);
		tabElement.tabChange('indexTab', id); //切换到：用户管理
	} else {
		tabElement.tabChange('indexTab', id); //切换到：用户管理
		return;
	}
	$(".left-menu").on("click","ul li",function(){
		$(this).siblings().removeClass("layui-nav-itemed");
	})
}
function lockPage(){
	layer.open({
		title : false,
		type : 1,
		content : $("#lock-box"),
		closeBtn : 0,
		shade : 0.6
	})
}


//左侧菜单切换
function leftMenuChange(id) {
	var ids = $(".left-menu ul dl a");
	var temp;
	$.each(ids, function(i, v) {
		if($(this).attr("data-id") == id) {
			temp = $(this);
		}
	});
	$(".left-menu ul dl dd").removeClass("layui-this");
	$(temp).parent().addClass("layui-this");
	$(".left-menu ul li").removeClass("layui-nav-itemed");
	$(temp).parent().parent().parent().addClass("layui-nav-itemed");
}
function convertMenuType(type) {
	// if (type == 3)
	// 	return '(OA)'
	// else if (type == 1)
	// 	return '(ERP)';
	// else
		return '';
}
function convertMenuUrl(type, url, token, params) {
	if (type == 1)
		return 'http://localhost:8094' + url + '?oauthToken=' + token  + params;
	else
		return url;
}